package com.hakim.wfb.web.controller.upload;

import com.alibaba.fastjson.JSONObject;
import com.hakim.wfb.web.utils.HttpUtil;
import com.hkfs.fundamental.api.data.ResultEx;
import com.hkfs.fundamental.common.utils.StrUtils;
import com.hkfs.fundamental.config.FundamentalConfigProvider;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.PartSource;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * @author tss
 * @version V1.0
 * @Title: UploadController
 * @Package com.hakim.oper.controller.Upload
 * @Description: ${todo}(用一句话描述该文件做什么)
 * @date 2016/6/15 11:03
 */
@Controller
@RequestMapping("/upload")
public class UploadController {
    private static final Logger logger = LoggerFactory.getLogger(UploadController.class);



    @RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> fileUpload(HttpServletRequest request,HttpServletResponse response) throws Exception {
        response.setCharacterEncoding("UTF-8");
        try {
            MultipartHttpServletRequest re = (MultipartHttpServletRequest) request;
            Map<String,MultipartFile> multipartFileMap = re.getFileMap();
            if(multipartFileMap == null){
                response.getWriter().write("{\"status\":false}");
                return null;
            }
            Map<String,Object> resultMap = new HashMap<>();
            for(Map.Entry<String,MultipartFile> entry : multipartFileMap.entrySet()){
                MultipartFile multipartFile = entry.getValue();
                if(!multipartFile.isEmpty()){
                    resultMap =  uploadOss(request,multipartFile);
                }
            }
            response.getWriter().write("{\"status\":true,\"url\":\""+resultMap.get("url").toString()+"\"}");
        } catch (IOException e) {
            logger.error(e.getMessage(),e);
            response.getWriter().write("{\"status\":false}");
        }
        return null;
    }


    @RequestMapping(value = "phoneUpload",name = "导入群发手机号码名单")
    @ResponseBody
    public ResultEx phoneUpload(HttpServletRequest request, HttpServletResponse response){
        response.setCharacterEncoding("UTF-8");
        List<String> extractList = new ArrayList<>();
        try {
            MultipartHttpServletRequest re = (MultipartHttpServletRequest) request;
            Map<String,MultipartFile> multipartFileMap = re.getFileMap();
            if(multipartFileMap == null){
                return new ResultEx().makeFailedResult("没有可导入的文件");
            }
            for(Map.Entry<String,MultipartFile> entry : multipartFileMap.entrySet()){
                MultipartFile multipartFile = entry.getValue();
                if(!multipartFile.isEmpty()){
                    List<String> phoneList = extractPhoneFromFile(multipartFile);
                    if(!phoneList.isEmpty()){
                        extractList.addAll(phoneList);
                    }
                }
            }
        } catch (Exception e) {
            return new ResultEx().makeFailedResult(e.getMessage());
        }
        ResultEx resultEx = new ResultEx();
        resultEx.setData(extractList);
        return resultEx.makeSuccessResult();

    }

    private List<String> extractPhoneFromFile(MultipartFile file){
        List<String> list = new ArrayList<>();
        try {
            String text = new String(IOUtils.toByteArray(file.getInputStream()));
            extractPhoneFromText(text,list);
        } catch (IOException e) {
            logger.error(e.getMessage(),e);
        }
        return list;
    }

    private void extractPhoneFromText(String text,List<String> list){
        if(StringUtils.isEmpty(text)){
            return;
        }
        String[] lines = text.split("\\r\\n");
        for(String line : lines){
            if(StrUtils.isPhoneNumber(line)){
                list.add(StrUtils.trim(line));
            }
        }

    }

    private  Map uploadOss(HttpServletRequest request,MultipartFile file) throws IOException{
        File file1 = File.createTempFile("oper"+new Date().getTime(),"."+file.getOriginalFilename().split("\\.")[1]);
        file.transferTo(file1);
        return  HttpUtil.uploadFile(request, FundamentalConfigProvider.getString("ossUrl"),"POST",new HashMap<>(),file1,"");
    }

    private  Map<String, Object> uploadOss(FileItem item) throws IOException{
        Map<String, Object> resMap = new HashMap<String, Object>();
        PostMethod postMethod = null;
        try {
            String postUrl = FundamentalConfigProvider.getString("ossUrl");
            postMethod = new PostMethod(postUrl + "/upload");
            byte[] file_data = streamToBytes(item.getInputStream(), true);
            PartSource source = new ByteArrayPartSource(item.getName(), file_data);
            FilePart fp = new FilePart("file", source);
            FilePart[] parts = { fp };
            HttpClient client = new HttpClient();
            MultipartRequestEntity formEntity = new MultipartRequestEntity(parts, postMethod.getParams());
            postMethod.setRequestEntity(formEntity);
            int status = client.executeMethod(postMethod);
            if (status == HttpStatus.SC_OK) {
                InputStream res = postMethod.getResponseBodyAsStream();
                byte[] data = streamToBytes(res, true);
                String result = new String(data,"UTF-8");
                JSONObject json = JSONObject.parseObject(result);
                String url = json.getString("url");
                resMap.put("retCode", 0);
                resMap.put("retMsg", "上传成功");
                resMap.put("url", url);
            } else {
                resMap.put("retCode", -1);
                resMap.put("retMsg", "上传失败");
                resMap.put("httpStatus", status);
            }
        } finally {
            postMethod.releaseConnection();
        }
        return resMap;
    }

    private static byte[] streamToBytes(InputStream is, boolean closeInputStream) {
        ByteArrayOutputStream baos = null;

        try {
            baos = new ByteArrayOutputStream();
            byte[] e = new byte[4096];
            boolean readedLen = true;

            int readedLen1;
            while(-1 != (readedLen1 = is.read(e))) {
                baos.write(e, 0, readedLen1);
            }

            byte[] bytes = baos.toByteArray();
            byte[] var6 = bytes;
            return var6;
        } catch (Exception var10) {
            logger.error("read bytes failed", var10);
        } finally {
            close(baos);
            if(closeInputStream) {
                close(is);
            }

        }

        return null;
    }

    public static void close(Closeable closeable) {
        if(null != closeable) {
            try {
                closeable.close();
            } catch (IOException var2) {
                logger.error("Close closeable faild: " + closeable.getClass(), var2);
            }
        }

    }

}
